<?php
/**
 * 接口核心
 */

use extend\ImgThumbnail;
use lib\supply\Order;
use lib\supply\xiaochu;
use sms\sms_operation;

include("../includes/fun.global.php");
include_once(SYSTEM_ROOT . "fun.admin.php");
include_once(SYSTEM_ROOT . "extend/GoodsImage.php");
@header('Content-Type: application/json; charset=UTF-8');

admin::safety('login,login_log,login_token,Send_verification_code_login,Send_verification_login,login_scan,login_app', $_QET);
/**勿动,防黑*/

switch ($_QET['act']) {
    case 'AppList': #应用列表
        $List = \lib\AppStore\AppList::acquire($_QET, $_QET['D']);
        dier($List);
        break;
    case 'app_install':#安装指定应用
        if (empty($_QET['id']) || empty($_QET['type'])) dies(-1, '请将参数填写完整');
        \lib\AppStore\AppList::install((int)$_QET['id'], (int)$_QET['type']);
        break;
    case 'app_unload': #卸载指定应用
        if (empty($_QET['id'])) dies(-1, '请将参数填写完整');
        \lib\AppStore\AppList::unload($_QET['id']);
        break;
    case 'app_view': #打开视图文件！
        @header('Content-Type: text/html; charset=UTF-8');
        if (empty($_QET['path']) || empty($_QET['id']) || empty((int)$_QET['t'])) show_msg('警告', '提交参数不完整！', false, false, false);
        \lib\AppStore\AppList::view($_QET['id'], $_QET['path'], (int)$_QET['t']);
        break;
    case 'app_state_set':
        if (empty($_QET['id']) || empty($_QET['type'])) dies(-1, '请将参数填写完整');
        \lib\AppStore\AppList::state_set($_QET['id'], $_QET['type']);
        break;
    case 'app_prolong': //延长到期时间
        if (empty($_QET['id'])) dies(-1, '请将参数填写完整');
        \lib\AppStore\AppList::prolong($_QET['id']);
        break;
    case 'app_update_log': //更新
        if (empty($_QET['id'])) dies(-1, '请将参数填写完整');
        $Data = \lib\AppStore\AppList::appdata($_QET['id']);
        dier($Data);
        break;
    case 'app_pay': //购买
        if (empty($_QET['id'])) dies(-1, '请将参数填写完整');
        \lib\AppStore\AppList::pay($_QET['id']);
        break;
    case 'app_users': //用户信息查询
        \lib\AppStore\AppList::users();
        break;
    case 'app_help':
        \lib\AppStore\AppList::AppHelp($_QET['id']);
        break;
    case 'prevent':
        if ($conf['prevent_switch'] == 1) {
            dies(1, \reward::prevent(is_https(false) . href(), 1));
        } else dies(1, is_https(false) . href());
        break;
    case 'product_list': #获取商品列表
        if ($_QET['type'] == null) {
            $id = (int)$_QET['id'];
            $al = $DB->get_row("SELECT * FROM `sky_shequ` WHERE `id` = $id  LIMIT 1");
            if (!$al) dies(-1, '货源不存在！');
            $_QET['type'] = $al['type'];
        }
        switch ($_QET['type']) {
            case 1:
                $arrays = community::__Data_acquisition_of_jiuwu(1, $_QET);
                $data_arr = json_decode($arrays, TRUE);
                if ($data_arr['goods_rows'] == '') {
                    dies(-1, '数据获取失败!请检查账号密码是否有误?');
                }
                $addt = [];
                foreach ($data_arr['goods_rows'] as $v) {
                    $addt[] = [
                        'gid' => $v['id'],
                        'type' => $v['goods_type'],
                        'title' => $v['title'],
                    ];
                }
                echo json_encode(array('code' => 1, 'msg' => '获取成功', 'data' => $addt));
                break;
            case 2:
                $arrays = community::__Eilek_data_acquisition(2, $_QET);
                $data_arr = json_decode($arrays, TRUE);
                if ($data_arr['status'] != '') {
                    dies(-1, '数据获取失败<br>' . $data_arr['message']);
                }
                $addt = [];
                foreach ($data_arr['data'] as $v) {
                    $addt[] = [
                        'gid' => $v['gid'],
                        'title' => $v['name'],
                    ];
                }
                dier([
                    'code' => 1,
                    'msg' => '获取成功',
                    'data' => $addt,
                ]);
                echo json_encode(array('code' => 1, 'msg' => '获取成功', 'data' => $addt));
                break;
            case 3: #小储系统对接
                $_QET['sqid'] = $_QET['id'];

                $List = xiaochu::GoodsListArr($_QET['sqid']);
                if ($List['state'] <> 1) dies(-1, (empty($List['msg']) ? '商品列表获取失败！' : $List['msg']));
                dier([
                    'code' => 1,
                    'msg' => '获取成功',
                    'data' => $List['data'],
                ]);
                break;
            case 4: #卡易信
                $_QET['sqid'] = $_QET['id'];
                switch ($_QET['kayixtype']) {
                    case '2': //获取目录下的商品
                        $ar_json = community::__Kamun_system(2, $_QET);
                        break;
                    default:
                        if ($_QET['cache'] == 3) { //获取余额
                            $ar_json = community::__Kamun_system(5, $_QET);
                        } else {
                            $ar_json = community::__Kamun_system(1, $_QET);
                        }
                        break;
                }
                die($ar_json);
                break;
        }
        break;
    case 'setGoodsSort': #修改商品排序
        $gid = intval($_QET['gid']);
        $type = intval($_QET['type']);
        if (shop::setSort($gid, $type, 1)) {
            dies(1, '修改成功!');
        } else {
            dies(-1, '修改失败!');
        }
        break;
    case 'setClassSort': #修改分类排序
        $cid = intval($_QET['cid']);
        $type = intval($_QET['type']);
        if (shop::setSort($cid, $type, 2)) {
            dies(1, '修改成功!');
        } else {
            dies(-1, '修改失败!');
        }
        break;
    case 'NewCarriageTemplate': //运费模板
        if (empty($_QET['name']) || empty($_QET['money']) || empty($_QET['nums']) || empty($_QET['exceed']) || empty($_QET['threshold'])) dies(-1, '请填写完整！');
        if ($_QET['state'] != -1) { //修改
            $re = $DB->query("UPDATE `sky_freight` SET `name`='{$_QET['name']}', `region`='{$_QET['region']}', `money`='{$_QET['money']}', `nums`='{$_QET['nums']}', `exceed`='{$_QET['exceed']}', `threshold`='{$_QET['threshold']}' WHERE (`id`='{$_QET['state']}');");
        } else {
            $re = $DB->query("INSERT INTO `sky_freight` (`name`, `region`, `money`, `nums`, `exceed`, `threshold`, `date`)
 VALUES ('{$_QET['name']}', '{$_QET['region']}', '{$_QET['money']}', '{$_QET['nums']}', '{$_QET['exceed']}', '{$_QET['threshold']}', '$date');");
        }
        if ($re) {
            dies(1, ($_QET['state'] != -1 ? '修改' : '添加') . '成功!');
        } else dies(-1, '执行失败:' . $DB->error());
        break;
    case 'setlevelSort': #修改等级排序
        $gid = intval($_QET['gid']);
        $type = intval($_QET['type']);
        if (shop::setSort($gid, $type, 3)) {
            dies(1, '修改成功!');
        } else {
            dies(-1, '修改失败!');
        }
        break;
    case 'order_remark': #填写订单备注
        $_QET['id'] = (int)$_QET['id'];
        $_QET['txt'] = (string)$_QET['txt'];
        if (empty($_QET['id']) || empty($_QET['txt'])) dies(-1, '请填写完整！');
        $re = $DB->query("UPDATE `sky_order` SET `remark`='{$_QET['txt']}' WHERE (`id`='{$_QET['id']}')");
        if ($re) {
            dies(1, '修改成功！');
        } else dies(-1, '修改失败' . $DB->error());
        break;
    case 'Goods_in_detail': #获取商品详细信息
        $id = (int)$_QET['id'];
        $al = $DB->get_row("SELECT * FROM `sky_shequ` WHERE `id` = $id  LIMIT 1");
        if (!$al) dies(-1, '货源不存在！');
        $_QET['type'] = $al['type'];
        $_QET['urls'] = $al['url'];
        $gid = $_QET['gid'];
        switch ($_QET['type']) {
            case 1: #玖伍
                $arrays = community::__Data_acquisition_of_jiuwu(2, $_QET);
                $data_arr = $arrays['data_1'];
                if ($data_arr['user_goods_lists_details'] == '') {
                    dies(-1, '数据获取失败!请检查账号密码是否有误?');
                }
                foreach ($data_arr['user_goods_lists_details'] as $v) {
                    if ($v['id'] == $_QET['gid']) {
                        if (!strstr($v['thumb'], 'http')) { #无图
                            if (!empty($v['thumb'])) {
                                $v['thumb'] = 'https://all-pt-upyun-cdn.95at.cn' . $v['thumb'];
                            }
                        }
                        $url = $al['url'] . '/index.php?m=home&c=goods&a=detail&id=' . $gid . '&goods_type=' . $v['goods_type'];
                        echo json_encode(array('code' => 1, 'msg' => '获取成功', 'data' => array(
                            'gid' => (int)$gid,
                            'name' => $v['title'],
                            'price' => (float)$v['goods_unitprice'],
                            'min' => (int)$v['minbuynum_0'],
                            'max' => (int)$v['maxbuynum_0'],
                            'image' => $v['thumb'],
                            'goods_type' => (int)$v['goods_type'],
                            'content' => $arrays['data_2']['docs'],
                            'inputs' => $arrays['data_2']['inpus'],
                            'pipei' => $arrays['data_2']['pipei'],
                            'url' => $url
                        )));
                        die();
                    }
                }
                break;
            case 2: #亿乐
                $arrays = community::__Eilek_data_acquisition(3, $_QET);
                $data_arr = json_decode($arrays, TRUE);
                if ($data_arr['data'] == '') {
                    dies(-1, '获取失败<br>' . $data_arr['message']);
                }
                $data_arr = $data_arr['data'];
                if (!strstr($data_arr['image'], 'http')) { #本地图片
                    if (!empty($data_arr['image'])) {
                        if (strstr($data_arr['image'], '!')) { //有水印
                            $ImageArra = explode('/', $data_arr['image']);
                            $ImageArra[count($ImageArra) - 1] = explode('!', $ImageArra[count($ImageArra) - 1])[0];
                            $data_arr['image'] = implode('/', $ImageArra);
                        }
                        $data_arr['image'] = 'http://' . $_QET['urls'] . '/' . $data_arr['image'];
                    }
                } else {
                    /**
                     * 去除水印
                     */
                    if (strstr($data_arr['image'], '!')) { //有水印
                        $ImageArra = explode('/', $data_arr['image']);
                        $ImageArra[count($ImageArra) - 1] = explode('!', $ImageArra[count($ImageArra) - 1])[0];
                        $data_arr['image'] = implode('/', $ImageArra);
                    }
                }
                $url = $al['url'] . '/home/order/' . $gid;
                echo json_encode(array('code' => 1, 'msg' => '获取成功', 'data' => array(
                    'gid' => (int)$gid,
                    'name' => $data_arr['name'],
                    'price' => (float)$data_arr['price'],
                    'min' => (int)$data_arr['limit_min'],
                    'max' => (int)$data_arr['limit_max'],
                    'content' => $data_arr['desc'],
                    'image' => $data_arr['image'],
                    'goods_type' => (int)$data_arr['cid'],
                    'inputs' => $data_arr['inputs'],
                    'pipei' => 'yile',
                    'url' => $url
                )));
                break;
            case 3: #小储系统
                $GoodsLog = xiaochu::GoodsArray($_QET['id'], $_QET['gid']);
                if ($GoodsLog['state'] <> 1) dies(-1, (empty($GoodsLog['msg']) ? '商品详情获取失败' : $GoodsLog['msg']));
                $data_arr = $GoodsLog['data'];
                $url = $al['url'] . '?cid=' . $data_arr['cid'] . '&gid=' . $gid;
                if (empty($data_arr['min']) && empty($data_arr['max'])) {
                    $max = 1;
                    $min = (int)$data_arr['quantity'];
                    if ($min == 1) {
                        $max = 1;
                    } elseif ($min > 1 && $min < 25) {
                        $max = $min * 1000;
                    } elseif ($min == 25) {
                        $max = 25;
                    } elseif ($min > 25 && $min < 100) {
                        $max = $min * 100000;
                    } elseif ($min >= 100) {
                        $max = $min * 1000000;
                    }
                } else {
                    $min = $data_arr['min'] - 0;
                    $max = $data_arr['max'] - 0;
                    if ($min == 0) {
                        $min = 1;
                    }
                    if ($max == 0) {
                        $max = $min * 1000000;
                    }
                }
                dier([
                    'code' => 1,
                    'msg' => '获取成功',
                    'data' => [
                        'gid' => (int)$gid,
                        'name' => $data_arr['name'],
                        'price' => (float)$data_arr['price'] / (int)$data_arr['quantity'],
                        'min' => $min,
                        'max' => $max,
                        'quantity' => (int)$data_arr['quantity'],
                        'content' => htmlspecialchars_decode($data_arr['content']),
                        'image' => $data_arr['image'],
                        'goods_type' => (int)$data_arr['cid'],
                        'inputs' => $data_arr['input'],
                        'pipei' => implode(',', $data_arr['inputs']),
                        'url' => $url,
                        'alert' => $data_arr['alert'],
                        'picture' => $data_arr['picture'],
                        'level' => $data_arr['level'],
                        'level_arr' => $data_arr['level_arr']
                    ]
                ]);
                break;
            case 4: #卡易信
                $_QET['gid'] = $_POST['gid'];
                $arrays = community::__Kamun_system(3, $_QET);
                die($arrays);
                break;
        }
        break;
    case 'Save_the_content': #保存商品数据
        /**
         * 验证基础参数
         */
        if (!isset($_QET['operation']) || !isset($_QET['profits']) || !isset($_QET['input']) || !isset($_QET['quota']) || !isset($_QET['money']) || !isset($_QET['quantity']) || !isset($_QET['name']) || !isset($_QET['state']) || !isset($_QET['cid'])) {
            dies(-1, '请填写完整！');
        }
        /**
         * 根据类型验证
         */
        switch ($_QET['operation']) {
            case '1': //自营
                $str = 'Gid,file,files,image,docs,alert,Picture,max,min'; #可以留空的参数
                array_key_yz($_QET, $str);
                break;
            case '2': //CURL
                $str = 'Gid,file,files,image,docs,alert,CURL_POST,Picture,max,min'; #可以留空的参数
                array_key_yz($_QET, $str);
                break;
            case '3': //卡密
                $str = 'Gid,file,files,image,docs,alert,Picture,max,min'; #可以留空的参数
                array_key_yz($_QET, $str);
                break;
            case '4': //货源社区
                $str = 'Gid,file,files,image,docs,alert,SupplyType,Picture,max,min'; #可以留空的参数
                array_key_yz($_QET, $str);
                break;
        }

        $method = [];
        foreach ($_QET['method'] as $v) {
            $method = array_merge($method, [(float)$v]);
        }
        $method = json_encode($method);

        if (!isset($_QET['freight'])) $_QET['freight'] = -1;
        if (!isset($_QET['profits'])) $_QET['profits'] = 100;
        if (!isset($_QET['custom'])) $_QET['custom'] = '';

        if (!isset($_QET['Gid'])) {
            $sort = $DB->get_row("SELECT sort FROM `sky_goods` ORDER BY `sort` DESC LIMIT 1 ");
            $sort = $sort['sort'] + 1;
            $a = $DB->query("INSERT INTO `sky_goods` (`custom`,`min`,`max`,`profits`,`freight`,`picture`,`goods_url`,`goods_mainKey`,`alert`,`sort`,`cid` ,`name`, `image`, `value`, `quota`, `quantity`, `goods_id`, `goods_type`,`docs`, `sqid` , `submit_the_field`,`money`,`state`,`curl`,`post_data`, `date`,`method`) 
            VALUES  ('{$_QET['custom']}','{$_QET['min']}','{$_QET['max']}','{$_QET['profits']}','{$_QET['freight']}','{$_QET['Picture']}','{$_QET['GoodsUrl']}' ,'{$_QET['GoodsMainKey']}' ,'{$_QET['alert']}','$sort','{$_QET['cid']}','{$_QET['name']}', '{$_QET['image']}', '{$_QET['input']}','{$_QET['quota']}', '{$_QET['quantity']}', '{$_QET['GoodsId']}', '{$_QET['GoodsType']}','{$_QET['docs']}','{$_QET['SupplyId']}',  '{$_QET['GoodsArguments']}','{$_QET['money']}','{$_QET['state']}','{$_QET['CURL_URL']}','{$_QET['CURL_POST']}', '$date' , '$method');");
            if ($a) {
                echo '{"code":1,"msg":"商品[' . $_QET['name'] . ']保存成功"}';
            } else echo '{"code":1,"msg":"商品[' . $_QET['name'] . ']保存失败:' . $DB->error() . '"}';
        } else {
            $gid = (int)$_QET['Gid'];
            $a = $DB->query("UPDATE `sky_goods` SET `custom` = '{$_QET['custom']}' , `min` = '{$_QET['min']}',`max` = '{$_QET['max']}',`profits` = '{$_QET['profits']}', `freight` = '{$_QET['freight']}' , `picture` = '{$_QET['Picture']}' , `goods_url` = '{$_QET['GoodsUrl']}' , `goods_mainKey` = '{$_QET['GoodsMainKey']}' , `alert` = '{$_QET['alert']}' ,  `name`='{$_QET['name']}', `image`='{$_QET['image']}', `money`='{$_QET['money']}', `value`='{$_QET['input']}',`cid`='{$_QET['cid']}', `quota`='{$_QET['quota']}', `quantity`='{$_QET['quantity']}', `docs`='{$_QET['docs']}', `sqid`='{$_QET['SupplyId']}', `goods_id`='{$_QET['GoodsId']}', `goods_type`='{$_QET['GoodsType']}', `submit_the_field`='{$_QET['GoodsArguments']}',`state` = '{$_QET['state']}',`curl` = '{$_QET['CURL_URL']}',`post_data` = '{$_QET['CURL_POST']}',`method` = '$method' WHERE (`gid`='$gid');");
            if ($a) {
                echo '{"code":1,"msg":"商品[' . $_QET['name'] . ']修改成功"}';
            } else echo '{"code":1,"msg":"商品[' . $_QET['name'] . ']修改失败:' . $DB->error() . '"}';
        }
        $DB->close();
        break;
    case 'BatchFreightTem': //获取商品的运费模板列表
        $rec = $DB->query("SELECT * FROM `sky_freight` ORDER BY `id` DESC ");
        $price_tem = [];
        while ($res = $DB->fetch($rec)) {
            $price_tem[] = ['id' => $res['id'], 'name' => $res['name']];
        }
        dier([
            'code' => 1,
            'data' => $price_tem,
        ]);
        break;
    case 'BatchFreightTemEdit': //批量设置商品的运费模板
        if (empty($_QET['id'])) dies(-1, '请填写完整！');
        $sql = '';
        foreach ($_QET['gid'] as $v) {
            $sql .= 'gid = ' . $v . ' or ';
        }
        $sql .= ' gid = ' . $_QET['gid'][0] . ' ;';
        $re = $DB->query("UPDATE `sky_goods` SET `freight`='{$_QET['id']}' WHERE $sql  ");
        if ($re) {
            dies(1, '操作成功');
        } else dies(-1, '操作失败！' . $DB->error());
        break;
    case 'BatchProfitEdit': //批量设置商品利润比例！
        if (empty((float)$_QET['profits'])) dies(-1, '请填写完整！');
        $sql = '';
        foreach ($_QET['gid'] as $v) {
            $sql .= 'gid = ' . $v . ' or ';
        }
        $sql .= ' gid = ' . $_QET['gid'][0] . ' ;';
        $re = $DB->query("UPDATE `sky_goods` SET `profits`='{$_QET['profits']}' WHERE $sql  ");
        if ($re) {
            dies(1, '操作成功');
        } else dies(-1, '操作失败！' . $DB->error());
        break;
    case 'ChangeOrders': #修改订单状态
        if (empty($_QET['id']) || empty($_QET['did'])) dies(-1, '请填写完整');

        if ($_QET['id'] == 8) { #删
            $a = $DB->query("DELETE FROM `sky_order` WHERE (`id`='{$_QET['did']}')");
        } else { #改
            if ($_QET['id'] == 5) { #退
                $re = $DB->get_row("SELECT * FROM `sky_order` WHERE (`id`='{$_QET['did']}')  LIMIT 1");
                if ($re['uid'] < 1) dies(-1, '游客订单无法进行退款操作！');
                $price = (float)$_QET['money'];
                if ($re['payment'] == '积分兑换') {
                    $msg = '管理员帮您在后台进行了退款操作，退款订单号为：' . $re['order'] . ',退款数为：' . round($price, 2) . $conf['currency'] . '！';
                    $DB->query("UPDATE `sky_user` SET `currency`=currency+$price WHERE (`id`='{$re['uid']}')");
                } else {
                    $msg = '管理员帮您在后台进行了退款操作，退款订单号为：' . $re['order'] . ',退款金额为：' . round($price, 2) . '元！';
                    $DB->query("UPDATE `sky_user` SET `money`=money+$price WHERE (`id`='{$re['uid']}')");
                }
                userlog('订单退款', $msg, $re['uid'], $price);
                $DB->query("UPDATE `sky_order` SET `remark`='$msg' WHERE (`id`='{$_QET['did']}')");
            }
            $a = $DB->query("UPDATE `sky_order` SET `state`='{$_QET['id']}' WHERE (`id`='{$_QET['did']}')");
        }
        if ($a) {
            dies(1, '操作成功');
        } else dies(-1, '操作失败！' . $DB->error());
        break;
    case 'replenishment': #补单
        if (empty($_QET['id'])) dies(-1, '请填写完整');
        Order::Retry($_QET['id']);
        //echo admin::replenishment($_QET);
        break;
    case 'order_details': #查询订单详情
        if (empty($_QET['id'])) dies(-1, '请填写完整');
        $id = (int)$_QET['id'];
        dier(Order::Query($id));
        break;
    case 'setGoodsShutDownlevel': #关闭等级密价
        if (empty((int)$_QET['gid'])) dies(-1, '请填写完整');
        $goods = $DB->get_row("SELECT * FROM `sky_goods` WHERE `gid` = '{$_QET['gid']}' LIMIT 1");
        if (!$goods) dies(-1, '商品不存在！');
        $arr = json_decode($goods['method'], TRUE);
        $method = [];
        foreach ($arr as $v) {
            if ($v == 8) continue;
            $method = array_merge($method, [$v]);
        }
        $method = json_encode($method);
        $re = $DB->query("UPDATE `sky_goods` SET `method` = '$method' WHERE (`gid`='{$_QET['gid']}')");
        if ($re) {
            die(json_encode(['code' => '1', 'msg' => '操作成功！']));
        } else die(json_encode(['code' => '1', 'msg' => '操作失败！' . $DB->error()]));
        break;
    case 'level_add': # 保存等级
        if (empty((int)$_QET['state']) || !isset($_QET['money']) || empty($_QET['name']) || empty($_QET['content']) || empty($_QET['priceis']) || empty($_QET['pointsis'])) dies(-1, '请填写完整');
        if ($_QET['state'] == -1) { //新建
            $sort = $DB->get_row("SELECT sort FROM `sky_price` ORDER BY `sort` DESC LIMIT 1 ");
            $sort = $sort['sort'] + 1;
            $re = $DB->query("INSERT INTO `sky_price` (`sort`, `name`, `content`, `priceis`, `pointsis`, `money`, `addtime`) VALUES ('$sort', '{$_QET['name']}', '{$_QET['content']}', '{$_QET['priceis']}', '{$_QET['pointsis']}', '{$_QET['money']}', '$date');");
        } else { //保存
            $re = $DB->query("UPDATE `sky_price` SET `name`='{$_QET['name']}' , `content`='{$_QET['content']}' , `money`='{$_QET['money']}' , `priceis`='{$_QET['priceis']}' , `pointsis`='{$_QET['pointsis']}'  WHERE (`mid`='{$_QET['state']}')");
        }
        if ($re) {
            die(json_encode(['code' => '1', 'msg' => '操作成功！']));
        } else die(json_encode(['code' => '1', 'msg' => '操作失败！' . $DB->error()]));
        break;
    case 'Goods_State_all': #批量调整商品状态
        $_QET['type'] = (int)$_QET['type'];
        if (empty($_QET['type']) || count($_QET['arr']) == 0 || empty($_QET['cid'])) dies(-1, '请填写完整');

        switch ($_QET['type']) {
            case 1: #上
                $SQL = "UPDATE `sky_goods` SET `state`='1' WHERE (`gid`=[GID])";
                break;
            case 2: #下
                $SQL = "UPDATE `sky_goods` SET `state`='2' WHERE (`gid`=[GID])";
                break;
            case 3: #删
                $SQL = "DELETE FROM `sky_goods` WHERE (`gid`=[GID])";
                break;
            case 4: #参数改
                $method = [];
                foreach ($_QET['cid'] as $k => $v) {
                    $method = array_merge($method, [$v + 0]);
                }
                $method = json_encode($method);
                $SQL = "UPDATE `sky_goods` SET `method`='$method' WHERE (`gid`=[GID])";
                break;
            case 5: #分类
                $SQL = "UPDATE `sky_goods` SET `cid`='{$_QET['cid']}' WHERE (`gid`=[GID])";
                break;
        }
        $msg = '';
        foreach ($_QET['arr'] as $v) {
            $SQLS = str_replace('[GID]', $v, $SQL);
            $re = $DB->query($SQLS);
            if ($re) {
                $msg .= '商品' . $v . '修改状态<font color=#66cdaa>成功！</font><br>';
            } else $msg .= $array = '商品' . $v . '修改状态<font color=red>失败！</font><br>';
        }
        dies(1, $msg);
        break;
    case 'set_order_all': #更新订单数据/批量
        $_QET['type'] = (int)$_QET['type'];
        if (empty($_QET['type']) || count($_QET['arr']) == 0) dies(-1, '请填写完整');
        $msg = '';
        foreach ($_QET['arr'] as $v) {
            $re = $DB->query("UPDATE `sky_order` SET `state`= '{$_QET['type']}' WHERE (`id`='$v')");
            if ($re) {
                $msg .= '订单' . $v . '修改状态<font color=#66cdaa>成功！</font><br>';
            } else $msg .= $array = '订单' . $v . '修改状态<font color=red>失败！</font><br>';
        }
        dies(1, $msg);
        break;
    case 'order_delete_all': #批量删除订单
        $_QET['type'] = (int)$_QET['type'];
        if (count($_QET['arr']) == 0) dies(-1, '请填写完整');
        $msg = '';
        foreach ($_QET['arr'] as $v) {
            $re = $DB->query("DELETE FROM `sky_order` WHERE (`id`='$v') ");
            if ($re) {
                $msg .= '订单' . $v . '删除<font color=#66cdaa>成功！</font><br>';
            } else $msg .= $array = '订单' . $v . '删除<font color=red>失败！</font><br>';
        }
        dies(1, $msg);
        break;
    case 'set_order': #更新订单数据
        $_QET['id'] = (int)$_QET['id'];
        if (empty($_QET['id']) || empty($_QET['input'])) dies(-1, '请填写完整');
        $input = json_decode($_POST['input'], TRUE);
        if (count($input) == 0) dies(-1, '数据结构解析异常,请检查是否输入有误?');
        $input = json_encode($input, JSON_UNESCAPED_UNICODE);
        $a = $DB->query("UPDATE `sky_order` SET `input`= '$input' WHERE (`id`='{$_QET['id']}')");
        if ($a) {
            die(json_encode(['code' => '1', 'msg' => '执行成功！']));
        } else die(json_encode(['code' => '1', 'msg' => '执行失败！' . $DB->error()]));
        break;
    case 'source_add': #添加修改/社区
        if (empty($_QET['type']) || empty($_QET['url']) || empty($_QET['user']) || empty($_QET['pass'])) dies(-1, '请填写完整');
        if ($_QET['dis'] <> '') {
            $a = $DB->query("UPDATE `sky_shequ` SET `url`='{$_QET['url']}', `type`='{$_QET['type']}', `username`='{$_QET['user']}', `password`='{$_QET['pass']}',`secret` = '{$_QET['secret']}' ,`pattern` = '{$_QET['pattern']}', `date`='$date' WHERE (`id`='{$_QET['dis']}');");
        } else {
            $a = $DB->query("INSERT INTO `sky_shequ` (`url`, `type`, `username`, `password`,`secret`,`pattern`, `date`) VALUES ('{$_QET['url']}', '{$_QET['type']}', '{$_QET['user']}', '{$_QET['pass']}','{$_QET['secret']}','{$_QET['pattern']}', '$date');");
        }
        if ($a) {
            die(json_encode(['code' => '1', 'msg' => '执行成功！']));
        } else die(json_encode(['code' => '1', 'msg' => '执行失败！' . $DB->error()]));
        break;
    case 'add_category': #添加/修改分类
        if (empty($_QET['name']) || empty($_QET['state']) || empty($_QET['image'])) dies(-1, '请填写完整');
        if ($_QET['dis'] <> '') {
            $a = $DB->query("UPDATE `sky_class` SET `content`='{$_POST['content']}' ,`name`='{$_QET['name']}', `image`='{$_QET['image']}', `state`='{$_QET['state']}', `date`='$date' WHERE (`cid`='{$_QET['dis']}');");
        } else {
            $sort = $DB->get_row("SELECT sort FROM `sky_class` ORDER BY `sort` DESC LIMIT 1 ");
            $sort = $sort['sort'] + 1;
            $a = $DB->query("INSERT INTO `sky_class` (`sort`, `name`, `image`,`content`, `state`, `date`) VALUES ('$sort', '{$_QET['name']}', '{$_QET['image']}','{$_POST['content']}', '{$_QET['state']}', '$date');");
        }
        if ($a) {
            die(json_encode(['code' => '1', 'msg' => '执行成功！']));
        } else die(json_encode(['code' => '1', 'msg' => '执行失败！' . $DB->error()]));
        break;
        break;
    case 'article_msg': #添加/修改商品
        if (empty($_QET['title']) || empty($_QET['date']) || empty($_QET['content'])) dies(-1, '请填写完整');
        $content = base64_encode($_QET['content']);
        if ($_QET['dis'] <> '') {
            $a = $DB->query("UPDATE `sky_notice` SET `title`= '{$_QET['title']}', `content`='$content', `browse`='{$_QET['browse']}', `date`='{$_QET['date']}' WHERE ( `id`='{$_QET['dis']}' ); ");
        } else {
            $a = $DB->query("INSERT INTO `sky_notice` ( `title`, `content`, `browse`, `date`) VALUES ( '{$_QET['title']}', '$content', '{$_QET['browse']}', '{$_QET['date']}' );");
        }
        if ($a) {
            die(json_encode(['code' => '1', 'msg' => '执行成功！']));
        } else die(json_encode(['code' => '1', 'msg' => '执行失败！' . $DB->error()]));
        break;
    case 'config_set': #保存网站信息
        $str = 'notice_top,notice_check,notice_bottom,notice_user,statistics,PopupNotice'; #basc64转换！
        $ar = admin::config($_QET, $str, $_POST);
        if ($ar) {
            config::unset_cache();
            die(json_encode(['code' => '1', 'msg' => '保存成功,本次成功保存' . count($ar) . '个数据！']));
        } else  die(json_encode(['code' => '1', 'msg' => '保存失败！']));
        break;
    case 'login_scan': //获取登陆二维码
        admin::login_scan();
        break;
    case 'login_app': #登陆后台APP
        admin::login_fa(2);
        break;
    case 'login': #登陆后台
        admin::login_fa(1);
        break;
    case 'login_log': #确认消息
        admin::login_log();
        break;
    case 'login_token': #确认消息2
        admin::login_token($_QET['token']);
        break;
    case 'index_update': #首页更新判断+日志检测
        admin::index_update();
        break;
    case 'data_header': #全局
        admin::data_header();
        break;
    case 'Get_notice_ch': #获取彩虹代刷公告
        admin::Get_notice_ch($_QET['url']);
        break;
    case 'Get_notice_xc': #获取小储系统公告
        admin::Get_notice_xc($_QET['url']);
        break;
    case 'image_content': #编辑器专用
        unset($_QET['act']);
        $ImageArr = [];
        foreach ($_QET as $key => $value) {
            if ($value['type'] <> 'image/png' && $value['type'] <> 'image/gif' && $value['type'] <> 'image/jpeg') dies(-1, '只可上传png/jpg/gif类型的图片文件！');
            $image = explode('.', $value["name"]);
            $timehtm = date('Ymd');
            mkdirs("../assets/img/image/" . $timehtm . '/');
            $image = $image['0'] . '.' . $image['1'];
            move_uploaded_file($value["tmp_name"], '../assets/img/image/' . $timehtm . '/' . $image);
            $images = '/assets/img/image/' . $timehtm . '/' . $image;
            new ImgThumbnail(ROOT . $images, $conf['compression'], ROOT . $images, 2);
            $ImageArr[] = ['src' => $images, 'size' => $value['size'] / 1000 . 'kb', 'name' => $value["name"]];
        }
        dier([
            'code' => 1,
            'msg' => '图片上传成功,本次共成功上传' . count($ImageArr) . '张图片',
            'SrcArr' => $ImageArr,
        ]);
        break;
    case 'image_up':#上传图片
        $image = explode('.', $_QET["file"]["name"]);
        if ($_QET["file"]['type'] <> 'image/png' && $_QET["file"]['type'] <> 'image/gif' && $_QET["file"]['type'] <> 'image/jpeg') dies(-1, '只可上传png/jpg/gif类型的图片文件！');
        $timehtm = date('Ymd');
        mkdirs("../assets/img/image/" . $timehtm . '/');
        $image = $image['0'] . '.' . $image['1'];
        move_uploaded_file($_QET["file"]["tmp_name"], '../assets/img/image/' . $timehtm . '/' . $image);
        $images = '/assets/img/image/' . $timehtm . '/' . $image;
        new ImgThumbnail(ROOT . $images, $conf['compression'], ROOT . $images, 2);
        echo json_encode(array('code' => 0, 'msg' => '上传成功,上传的图片大小为：' . $_QET['file']['size'] / 1000 . 'kb', 'src' => $images));
        break;
    case 'conversion':
        admin::conversion($_QET);
        break;
    case 'note_set': #商品备注信息
        if (empty($_QET['note']) || empty($_QET['gid'])) dies(-1, '参数不完整！');
        $re = $DB->query("UPDATE `sky_goods` SET `note`='{$_QET['note']}' WHERE (`gid`='{$_QET['gid']}')");
        if ($re) {
            dies(1, '备注设置成功！');
        } else dies(-1, '备注设置失败' . $DB->error());
        break;
    case 'kami_add': #添加卡密
        if (empty($_QET['kam_arr']) || empty($_QET['gid'])) dies(-1, '参数不完整！');
        if (count($_QET['kam_arr']) == 0) dies(-1, '请添加多张卡密！');
        $_QET['gid'] = (int)$_QET['gid'];
        $a = 0;
        $b = 0;
        foreach ($_QET['kam_arr'] as $v) {
            if ($v == '') continue;
            $ar = $DB->query("INSERT INTO `sky_token` (`gid`, `token`, `addtime`) VALUES ('{$_QET['gid']}', '$v', '$date')");
            if ($ar) {
                $a++;
            } else $b++;
        }
        dies(1, '本次成功添加' . $a . '张卡密！,失败' . $b . '张！');
        break;
    case 'kami_empty': #清空卡密
        if ($_QET['gid'] <> '') {
            $sql = 'WHERE `gid` = ' . (int)$_QET['gid'] . ' ';
        }
        $a = $DB->query("DELETE FROM `sky_token` $sql ");
        if ($a) {
            dies(1, '卡密清空成功！');
        } else dies(-1, '卡密清空失败' . $DB->error());
        break;
    case 'kami_empty_use': #清空库存卡
        if ($_QET['gid'] <> '') {
            $sql = "WHERE `gid` = " . (int)$_QET['gid'] . " AND `endtime` is not null ";
        } else {
            $sql = "WHERE  `endtime` is not null ";
        }
        $a = $DB->query("DELETE FROM `sky_token` $sql ");
        if ($a) {
            dies(1, '卡密清空成功！');
        } else dies(-1, '卡密清空失败' . $DB->error());
        break;
    case 'sms_data': #获取短信信息
        $sms = new sms_operation(href(), $accredit['token']);
        $sms->user_data();
        break;
    case 'config_set_sms': #保存短信配置
        if (empty($_QET['sms_switch_user']) || empty($_QET['sms_switch_order']) || empty((int)$_QET['Mobile'])) dies(-1, '请填写完整！');
        $sms = new sms_operation(href(), $accredit['token']);
        $str = '';
        $arr = ['sms_switch_user' => $_QET['sms_switch_user'], 'sms_switch_order' => $_QET['sms_switch_order'], 'weix_notice' => $_QET['weix_notice']];
        $smsset = $sms->user_data_set((int)$_QET['Mobile']);
        $ar = admin::config($arr, $str, $arr);
        if ($ar && $smsset == true) {
            config::unset_cache();
            die(json_encode(['code' => '1', 'msg' => '保存成功,本次成功保存' . (count($ar) + 1) . '个数据！']));
        } else  die(json_encode(['code' => '1', 'msg' => '保存失败！']));
        break;
    case 'Send_verification_code_login': #短信登陆
        if (empty((int)$_QET['mobile'])) dies(-1, '请将手机号填写完整！');
        $sms = new sms_operation(href(), $accredit['token'], 1);
        $arr = $sms->admin_login((int)$_QET['mobile']);
        dier($arr);
        break;
    case 'Send_verification_login': #短信验证
        if (empty((int)$_QET['code'])) dies(-1, '请将验证码填写完整！');
        $sms = new sms_operation(href(), $accredit['token'], 1);
        $arr = $sms->admin_login_verify((int)$_QET['code']);
        dier($arr);
        break;
    case 'admin_ip': //服务器IP地址
        $a = get_curl(is_https(false) . href() . '/api.php?act=ip');
        echo $a;
        break;
    case 'withdraw_deposit':
        $page = ((int)$_GET['page'] - 1) * (int)$_GET['limit']; //页码
        $limit = (int)$_GET['limit'];
        $data = $DB->query("SELECT * FROM `sky_withdrawal` order by id desc limit $page,$limit ");
        $count = $DB->count("SELECT count(*) FROM sky_withdrawal ");
        $data_arr = [];
        while ($re = $DB->fetch($data)) {
            $timehtm = md5($re['uid'] . '小储云');
            $images = '/assets/img/withdraw/' . $timehtm . '/' . $re['uid'] . '.png?time=' . time();
            $re['image'] = $images;
            $re['arrival_money'] = round($re['money'] - (($conf['userdepositservice'] / 100) * $re['money']), 2);
            $data_arr[] = $re;
        }
        die(json_encode([
            'code' => 0,
            'msg' => '数据获取成功',
            'count' => $count,
            'data' => $data_arr
        ]));
        break;
    case 'withdraw_deposit_data': #获取提现数据，计算单用户总待提现金额
        $id = (int)$_QET['id'];
        if (empty($id)) dies(-1, '请填写完整！');
        $data = $DB->get_row("SELECT * FROM  `sky_withdrawal` WHERE `id` = $id ");
        if (!$data) dies(-1, '数据获取失败！');
        if ($data['state'] == 3) { //待处理
            $count = $DB->count("SELECT count(*) FROM `sky_withdrawal` WHERE `uid` = {$data['uid']} AND `state` = 3 ");
            //获取相同的数据
            $timehtm = md5($data['uid'] . '小储云');
            $images = '/assets/img/withdraw/' . $timehtm . '/' . $data['uid'] . '.png?time=' . time();
            $count_pay_1 = $DB->count("SELECT sum(money) FROM `sky_withdrawal` WHERE `uid` = {$data['uid']} AND `state` = 3 ");
            if ($count > 1) { //有多个待提现数据！
                $count_pay = $DB->count("SELECT sum(money) FROM `sky_withdrawal` WHERE `uid` = {$data['uid']} AND `state` = 3 ");
                $data_arr = [
                    'code' => 1,
                    'msg' => '数据获取成功',
                    'uid' => $data['uid'],
                    'money_ar' => $count_pay_1,
                    'money' => round($count_pay_1 - (($conf['userdepositservice'] / 100) * $count_pay_1), 2),
                    'account' => $data['account_number'], //收款账号
                    'name' => $data['name'],
                    'remark' => $data['remarks'],
                    'image' => $images,
                    'count' => $count
                ];
            } else { //只有一个
                $data_arr = [
                    'code' => 1,
                    'msg' => '数据获取成功',
                    'uid' => $data['uid'],
                    'money_ar' => $count_pay_1,
                    'money' => round($count_pay_1 - (($conf['userdepositservice'] / 100) * $count_pay_1), 2),
                    'account' => $data['account_number'], //收款账号
                    'name' => $data['name'],
                    'remark' => $data['remarks'],
                    'image' => $images,
                    'count' => 1
                ];
            }
            dier($data_arr);
        } else { //删除
            $re = $DB->query("DELETE FROM `sky_withdrawal` WHERE (`id`='$id')");
            if ($re) {
                dies(2, '删除成功');
            } else dies(-1, '删除失败');
        }
        break;
    case 'withdraw_deposit_result':
        if (empty($_QET['uid']) || empty($_QET['id']) || empty($_QET['type']) || empty($_QET['money'])) dies(-1, '请填写完整！');
        switch ($_QET['type']) {
            case 1:
                $re = $DB->query("UPDATE `sky_withdrawal` SET `state`='1', `result_code`='{$_QET['result']}', `endtime`='$date' WHERE `uid` = '{$_QET['uid']}' AND `state` = 3 ");
                break;
            case 2:
                $re = $DB->query("UPDATE `sky_withdrawal` SET `state`='2', `result_code`='{$_QET['result']}', `endtime`='$date' WHERE `uid` = '{$_QET['uid']}' AND `state` = 3 ");
                break;
        }
        if ($re) {
            if ($_QET['type'] == 1) {
                $get = $DB->get_row("SELECT * FROM `sky_user` WHERE `id` = '{$_QET['uid']}' ");
                userlog('提现成功', '管理员已经帮您处理提现，累计提现金额为：' . $_QET['money'] . ',再接再厉！', $_QET['uid'], $_QET['money']);
            } else { //退款
                userlog('提现失败', '提现审核失败(' . $_QET['result'] . ')金额' . $_QET['money'] . '元已退回到您的账户！', $_QET['uid'], $_QET['money']);
                $MONEYS = (float)$_QET['money'];
                @$DB->query("UPDATE `sky_user` SET `money`= money+$MONEYS  WHERE (`id`='{$_QET['uid']}')");
            }
            dies(1, '提现状态修改成功！');
        } else dies(-1, '提现处理失败！');
        break;
    case 'security_filename_log':
        $page = ((int)$_GET['page'] - 1) * (int)$_GET['limit'];
        $limit = (int)$_GET['limit'] + $page;
        $CONTENT = json_decode(file_get_contents(ROOT . "includes/extend/log/safety/" . $_QET['filename']), TRUE);

        $array = [];
        $list = 0;
        foreach ($CONTENT as $key => $value) {
            ++$list;
            if ($list >= $page && $list <= $limit) {
                $value['date'] = $key;
                $array[] = $value;
            } else continue;
        }
        dier([
            'code' => 0,
            'msg' => '日志获取成功',
            'count' => count($CONTENT),
            'data' => $array
        ]);

        break;
    case 'security_log':
        $page = ((int)$_GET['page'] - 1) * (int)$_GET['limit'];
        $limit = (int)$_GET['limit'] + $page;
        $dir = ROOT . "includes/extend/log/safety/";
        $file = scandir($dir);
        $array = [];
        $list = 0;
        foreach (array_reverse($file) as $value) {
            if ($value == '.' || $value == '..') continue;
            ++$list;
            if ($list >= $page && $list <= $limit) {
                $arr = explode('_', $value);
                $CONTENT = json_decode(file_get_contents(ROOT . "includes/extend/log/safety/" . $value), TRUE);
                $array[] = ['date' => explode('.', $arr[1])[0], 'filename' => $value, 'count' => count($CONTENT) . '条'];
            } else continue;

        }
        dier([
            'code' => 0,
            'msg' => '日志获取成功',
            'count' => count($file) - 2,
            'data' => $array
        ]);
        break;
    case 'OrderDel':
        if (empty((int)$_QET['id'])) dies(-1, '请填写完整！');
        $res = $DB->query("DELETE FROM `sky_queue` WHERE `id`='$id' ");
        if ($res) {
            dies(1, '编号' . $id . '的订单已经成功删除！');
        } else dies(-1, '未付款订单删除失败');
        break;

    case 'Tickets': //工单管理
        if (!isset($_QET['type'])) dies(-1, '请填写完整');
        $DB = \Medoo\DB\SQL::DB();
        switch ($_QET['type']) {
            case 'list':
                if ($_QET['state'] == 'all') {
                    $List = $DB->select('tickets', ['id', 'name', 'class', 'type', 'state', 'addtime', 'grade'], ['ORDER' => ['id' => 'DESC']]);
                } else {
                    $List = $DB->select('tickets', ['id', 'name', 'class', 'type', 'state', 'addtime', 'grade'], ['state' => $_QET['state'], 'ORDER' => ['id' => 'DESC']]);
                }
                dier([
                    'code' => 1,
                    'msg' => '工单列表获取成功',
                    'data' => $List,
                ]);
                break;
            case 'details': //工单详情
            case 'Supplementary': //补充内容
            case 'Finish': //完结工单
                $Tickets = $DB->get('tickets', '*', ['id' => $_QET['id']]);
                if (!$Tickets) dies(-1, '订单不存在！');
                if ($Tickets['message'] == '') {
                    $Data = [];
                } else {
                    $Data = \config::common_unserialize($Tickets['message']);
                }
                if ($_QET['type'] == 'details') {
                    dier([
                        'code' => 1,
                        'msg' => '数据获取成功',
                        'data' => $Data,
                        'class' => $Tickets['class'],
                        'time' => $Tickets['timetips'],
                        'order' => ($Tickets['order'] == null ? '无相关订单' : $Tickets['order']),
                        'state' => $Tickets['state'],
                        'grade' => $Tickets['grade'],
                        'count' => count($Data),
                        'type' => $Tickets['type'],
                    ]);
                } else if ($_QET['type'] == 'Supplementary') {
                    if ($Tickets['type'] == 4) dies(-1, '此工单已经关闭,请重新创建新的工单！');
                    if ($Tickets['type'] >= 3 || $Tickets['state'] == 3) dies(-1, '工单已完结,若要提交内容请创建新的工单!');

                    $Data = array_merge($Data, [
                        $date => [
                            'type' => 2,
                            'content' => $_QET['content'],
                        ]
                    ]);

                    $Res = $DB->update('tickets', [
                        'message' => $Data,
                        'type' => 2,
                    ], [
                        'id' => $_QET['id'],
                    ]);
                    if ($Res) {
                        dies(1, '工单回复成功！');
                    } else dies(-1, '工单回复失败');
                } else if ($_QET['type'] == 'Finish') {
                    $Res = $DB->update('tickets', [
                        'state' => 3,
                        'type' => 4,
                        'endtime' => $date,
                    ], [
                        'id' => $_QET['id'],
                    ]);
                    if ($Res) {
                        if ($Tickets['order'] <> '不选择相关订单') {
                            @$DB->update('order', ['state' => 1], ['order' => $Tickets['order']]);
                        };
                        dies(1, '工单[' . $_QET['id'] . ']成功关闭,用户将无法回复工单！');
                    } else dies(-1, '关闭失败！');
                }
                break;
            default:
                dies(-1, '403');
                break;
        }
        break;
    case 'Mark': //评论管理
        $DB = \Medoo\DB\SQL::DB();
        switch ($_QET['type']) {
            case 'List':
                $Res = $DB->select('mark', '*', [
                    'ORDER' => [
                        'id' => 'DESC'
                    ],
                    'LIMIT' => [(($_QET['page'] - 1) * $_QET['limit']), $_QET['limit']],
                ]);
                $Count = $DB->count('mark', '*');
                dier([
                    'code' => 0,
                    'msg' => '获取成功',
                    'data' => $Res,
                    'count' => $Count,
                ]);
                break;
            case 'state':
                if ($_QET['state'] == 4) {
                    $Res = $DB->delete('mark', ['id' => $_QET['id']]);
                } else {
                    $Res = $DB->update('mark', [
                        'state' => $_QET['state'],
                    ], ['id' => $_QET['id']]);
                }
                if ($Res) {
                    dies(1, '操作成功');
                } else dies(-1, '评论审核失败!');
                break;
        }
        break;
    default:
        dies(-1, '403');
        break;
}